package com.jtw.common.util;

import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.CookieManager;
import com.gargoylesoftware.htmlunit.NicelyResynchronizingAjaxController;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HTMLParserListener;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.util.WebClientUtils;
import com.jtw.common.jwt.MouseCtrl;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.Transferable;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.util.Collections;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * DESCRIPT: 爬虫辅助类
 *
 * @author cjsky666
 * @date 2019/9/8 13:43
 */
public class SpiderUtil {

    public static final int  timeout= 12000;
    public static final int speed = 500;//抓取频率

    public static HttpURLConnection connection = null;

    /**
     * 创建http对象
     * @param path 访问的路径
     * @param httpMethod http请求的方式
     * @param timeout 超时时间
     * @return
     */
    public static HttpURLConnection create(String path,String httpMethod){
        URL url = null;
        try {
            url = new URL(path);
            connection = (HttpURLConnection)url.openConnection();
            //默认就是Get，可以采用post，大小写都行，因为源码里都toUpperCase了。
            connection.setRequestMethod(httpMethod==null?"GET":httpMethod);
            //是否允许缓存，默认true。
            connection.setUseCaches(Boolean.FALSE);
            //是否开启输出输入，如果是post使用true。默认是false
            //connection.setDoOutput(Boolean.TRUE);
            //connection.setDoInput(Boolean.TRUE);
            //设置请求头信息
            connection.addRequestProperty("Connection", "close");
//设置连接主机超时（单位：毫秒）
            connection.setConnectTimeout(5000);
            //设置从主机读取数据超时（单位：毫秒）
            connection.setReadTimeout(timeout);
//设置Cookie
//            connection.addRequestProperty("Cookie","你的Cookies" );
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            connection.disconnect();
        }
        return connection;
    }

    /**
     * 根据url获取页面元素
     * @param url 路径
     * @return
     */

    public static Document getDocumentByURL(String url,String httpMethod,String charset){
        try {
            return Jsoup.parse(create(url,httpMethod).getInputStream(),charset,url);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 采用htmlunit获取网页，并解析执行js，渲染页面
     */
    public static Document getDocumentByChrome(String url){
        System.getProperties().put("org.apache.commons.logging.simplelog.defaultlog", "warn");
        WebClient webClient=new WebClient(BrowserVersion.CHROME);
//        webClient.setCookieManager(new CookieManager().getCookie());
//        webClient.setHTMLParserListener(HTMLParserListener.LOG_REPORTER);
        //当JS执行出错的时候是否抛出异常, 这里选择不需要
        webClient.getOptions().setThrowExceptionOnScriptError(false);
        //当HTTP的状态非200时是否抛出异常, 这里选择不需要
        webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
        //启用javascript
        webClient.getOptions().setJavaScriptEnabled(true);
        // 设置客戶端重定向
        webClient.getOptions().setRedirectEnabled(true);
        //关闭css渲染效果
        webClient.getOptions().setCssEnabled(false);
        //关闭windows的ie插件
        webClient.getOptions().setActiveXNative(false);
        //设置支持ajax
        webClient.setAjaxController(new NicelyResynchronizingAjaxController());
        webClient.getOptions().setTimeout(50000);
        try {
            HtmlPage htmlPage = webClient.getPage(url);
            webClient.waitForBackgroundJavaScript(30000);
            return Jsoup.parse(htmlPage.asXml());
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            webClient.close();
        }
        return null;
    }

    public static void openVirtualWebBrowerChrome(){
//      System.setProperty("webdriver.msedge.driver", "C:\\driver\\msedgedriver.exe");
//      System.setProperty("webdriver.msedge.driver", "C:\\driver\\msedgedriver.exe");
        System.setProperty("webdriver.chrome.driver", "C:\\driver\\chromedriver.exe");
        ChromeOptions opt = new ChromeOptions();
        opt.setExperimentalOption("excludeSwitches",Collections.singletonList("enable-automation"));
        WebDriver driver = new ChromeDriver(opt);
        Actions action = new Actions(driver);
        driver.manage().window().maximize();
        driver.get("https://login.zhipin.com/?ka=header-login");
        WebElement account = new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.name("account")));
        WebElement password = new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.name("password")));
        WebElement btn_slide = new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.className("btn_slide")));
        action.moveToElement(account).perform();
        account.click();
        account.sendKeys("111111");
        action.moveToElement(password).perform();
        password.click();
        password.sendKeys("123");
        action.moveToElement(btn_slide).perform();
        action.dragAndDropBy(btn_slide,500,Integer.valueOf(RandomUtil.getNumber(1))).perform();
//        action.moveByOffset(500,Integer.valueOf(RandomUtil.getNumber(1))).perform();
        String title = driver.getTitle();
        System.out.println(title);
        driver.close();
    }

    public  static void openChromeRelease(String url){
//        String path = "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe";
        if(Desktop.isDesktopSupported()) {
            URI uri = URI.create(url);
            Desktop desktop = Desktop.getDesktop();
            if(desktop.isSupported(Desktop.Action.BROWSE)) {
                try {
                    desktop.browse(uri);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    /**
     * 【960,663】滑块按钮位置
     * 【1620,663】滑块拉到最右边的位置
     * 【1099,757】 登录按钮的位置
     * 【96,475】 推荐牛人的屏幕坐标
     * @param args
     */
    public static void main(String[] args) {
//        openVirtualWebBrowerChrome();
//        openChromeRelease("https://login.zhipin.com/?ka=header-login");
        Runnable runnable = new Thread() {
            @Override
            public void run() {
                MouseCtrl.printMouseLocation();
            }
        };
        ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
        executor.scheduleAtFixedRate(runnable, 1, 3, TimeUnit.SECONDS);
//        MouseCtrl.Move(960,663);
//        MouseCtrl.robot.mousePress(InputEvent.BUTTON1_MASK);
//        MouseCtrl.Move(1620,663);
//        MouseCtrl.robot.mouseRelease(InputEvent.BUTTON1_MASK);
//        MouseCtrl.Move(1099,757);
//        MouseCtrl.robot.mousePress(InputEvent.BUTTON1_MASK);
//        MouseCtrl.robot.mouseRelease(InputEvent.BUTTON1_MASK);
        MouseCtrl.keyPressWithAlt(KeyEvent.VK_TAB);
        MouseCtrl.Move(96,475);
        MouseCtrl.robot.mousePress(InputEvent.BUTTON1_MASK);
        MouseCtrl.robot.mouseRelease(InputEvent.BUTTON1_MASK);
        System.out.println(MouseCtrl.getClipboardString());
    }

}
